package com.yuexunit.mobilenurse.module.SkinTest.ui;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.base.titlebar.TitleBar_DocAdvice;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.Login.bean.SystemConfig;
import com.yuexunit.mobilenurse.module.Login.bean.YXLoginData;
import com.yuexunit.mobilenurse.module.Login.model.impl.LoginModel;
import com.yuexunit.mobilenurse.module.Login.presenter.IUserPresenter;
import com.yuexunit.mobilenurse.module.Login.presenter.impl.UserPresenter;
import com.yuexunit.mobilenurse.module.Login.ui.view.IUserView;
import com.yuexunit.mobilenurse.module.SkinTest.bean.SkinTestDetailBean;
import com.yuexunit.mobilenurse.module.SkinTest.bean.YXSkinTestExecBean;
import com.yuexunit.mobilenurse.module.SkinTest.model.impl.SkinTestDetailModel;
import com.yuexunit.mobilenurse.module.SkinTest.presenter.ISkinTestDetailPresenter;
import com.yuexunit.mobilenurse.module.SkinTest.presenter.impl.SkinTestDetailPresenter;
import com.yuexunit.mobilenurse.module.SkinTest.ui.view.ISkinTestDetailView;
import com.yuexunit.mobilenurse.receiver.SkinTestReceiver;
import com.yuexunit.mobilenurse.util.ActionSheetDialog;
import com.yuexunit.mobilenurse.util.LoginDialog;
import com.yuexunit.mobilenurse.util.timeUtil.CustomDatePicker;
import com.yuexunit.mobilenurse.widget.FixedSwipeListView;

import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;
import org.kymjs.kjframe.utils.SystemTool;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/3/13 0013.
 */

public class Act_SkinTest_Detail extends TitleBar_DocAdvice implements ISkinTestDetailView, IUserView {

    @Bind(R.id.titlebar_docadvice_tv_title)
    TextView titlebarDocadviceTvTitle;
    @Bind(R.id.docactvice_name)
    TextView docactviceName;
    @Bind(R.id.docactvice_bedno)
    TextView docactviceBedno;
    @Bind(R.id.docactvice_visitno)
    TextView docactviceVisitno;
    @Bind(R.id.do_date)
    EditText doDate;
    @Bind(R.id.drug_list)
    FixedSwipeListView drugList;
    @Bind(R.id.skin_start_time)
    TextView skinStartTime;
    @Bind(R.id.skin_start_name)
    TextView skinStartName;
    @Bind(R.id.skin_detail_start_ll_01)
    LinearLayout skinDetailStartLl01;
    @Bind(R.id.skin_detail_start_ll_02)
    LinearLayout skinDetailStartLl02;
    @Bind(R.id.skin_result)
    TextView skinResult;
    @Bind(R.id.skin_complex_name_01)
    TextView skinComplexName01;
    @Bind(R.id.skin_complex_time_01)
    TextView skinComplexTime01;
    @Bind(R.id.skin_complex_name_02)
    TextView skinComplexName02;
    @Bind(R.id.skin_complex_time_02)
    TextView skinComplexTime02;
    @Bind(R.id.skin_detail_end_ll_02)
    LinearLayout skinDetailEndLl02;
    @Bind(R.id.skin_detail_end_ll_01)
    LinearLayout skinDetailEndLl01;
    @Bind(R.id.time_15)
    RadioButton time15;
    @Bind(R.id.time_20)
    RadioButton time20;
    @Bind(R.id.skin_detail_time_ll)
    LinearLayout skinDetailTimeLl;

    private String Visitno, psh, fhId;
    ISkinTestDetailPresenter presenter;

    private boolean isEdit = true;

    LoginDialog loginDialog;
    private IUserPresenter userPresenter;

    //闹钟计数
    private SharedPreferences sharedPreferences;
    SkinTestDetailBean skinTestDetailBean;

    int time =0;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_skintest_detail);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        sharedPreferences = this.getSharedPreferences("skintest", Context.MODE_WORLD_READABLE);
        userPresenter = new UserPresenter(this, new LoginModel());
        presenter = new SkinTestDetailPresenter(this, new SkinTestDetailModel());
        Visitno = PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO);
        psh = getIntent().getExtras().getString("psh");
        if (SystemTool.checkNet(aty)) {
            presenter.showSkinTestDetail(psh);
        } else {
            ViewInject.toast("网络异常，请检查网络是否连接!");
        }
    }

    @Override
    public void setTitle() {
        titlebarDocadviceTvTitle.setText("皮试详情");
        docactviceName.setText(PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_NAME));
        docactviceBedno.setText(PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_BEDCODE));
        docactviceVisitno.setText(PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO));
    }

    @OnClick({R.id.titlebar_docadvice_img_back_ll, R.id.skin_start, R.id.skin_result_ll, R.id.skin_complex_time_ll_01, R.id.skin_complex_name_ll_02, R.id.skin_complex_time_ll_02, R.id.skin_end})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titlebar_docadvice_img_back_ll:
                finish();
                break;
            case R.id.skin_start:
                if(time15.isChecked())
                {
                    time=15;
                }
                else if(time20.isChecked())
                {
                    time=20;
                }
                if(time!=0) {
                    presenter.startSkinTest(psh, doDate.getText().toString(), PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_LOGID));
                }
                else {
                    ViewInject.toast("请选择皮试时长");
                }
                break;
            case R.id.skin_result_ll:
                if (isEdit) {
                    selectIdea();
                }
                break;
            case R.id.skin_complex_time_ll_01:
                if (isEdit) {
                    initTimePicker(0);
                }
                break;
            case R.id.skin_complex_name_ll_02:
                if (isEdit) {
                    loginDialog = new LoginDialog(aty).builder();
                    loginDialog.setCallBack(new LoginDialog.ICallBack() {
                        @Override
                        public void callback(Bundle bundle) {
                            if (bundle != null) {
                                fhId = bundle.getString("person_num");
                                userPresenter.doInLogin(bundle.getString("person_num"), bundle.getString("person_psw"));
                            }
                        }
                    });
                    loginDialog.show();
                }
                break;
            case R.id.skin_complex_time_ll_02:
                if (isEdit) {
                    initTimePicker(1);
                }
                break;
            case R.id.skin_end:
                if (skinResult.getText().toString().length() > 0 && skinComplexName01.getText().toString().length() > 0
                        && skinComplexTime01.getText().toString().length() > 0 && skinComplexName02.getText().toString().length() > 0
                        && skinComplexTime02.getText().toString().length() > 0) {
                    String result = "";
                    if (skinResult.getText().toString().equals("阴性")) {
                        result = "Y";
                    } else if (skinResult.getText().toString().equals("阳性")) {
                        result = "N";
                    } else if (skinResult.getText().toString().equals("脱敏")) {
                        result = "T";
                    }

                    presenter.endSkinTest(psh, result,
                            PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_LOGID), skinComplexTime01.getText().toString() + ":00",
                            fhId, skinComplexTime02.getText().toString() + ":00");
                }
                break;
        }
    }

    @Override
    public void onBackClick() {
        finish();
    }

    @Override
    public void showSkinTestDetail(SkinTestDetailBean skinTestDetailBean) {
        this.skinTestDetailBean = skinTestDetailBean;
        if (this.skinTestDetailBean.getPskssj() != null && this.skinTestDetailBean.getPskssj().length() > 0) {
            skinDetailTimeLl.setVisibility(View.GONE);
            skinDetailStartLl01.setVisibility(View.VISIBLE);
            if (this.skinTestDetailBean.getPspc() != null) {
                doDate.setText(this.skinTestDetailBean.getPspc());
            }
            doDate.setFocusable(false);
            skinStartTime.setText(this.skinTestDetailBean.getPskssj());
            skinStartName.setText(this.skinTestDetailBean.getPsry());
            skinDetailStartLl02.setVisibility(View.GONE);

            skinDetailEndLl01.setVisibility(View.VISIBLE);
            if (this.skinTestDetailBean.getPsjg() != null && this.skinTestDetailBean.getPsjg().length() > 0) {
                isEdit = false;
                String result = "";
                if (this.skinTestDetailBean.getPsjg().equals("Y")) {
                    result = "阴性";
                } else if (this.skinTestDetailBean.getPsjg().equals("N")) {
                    result = "阳性";
                } else if (this.skinTestDetailBean.getPsjg().equals("T")) {
                    result = "脱敏";
                }
                skinResult.setText(result);
                skinComplexName01.setText(this.skinTestDetailBean.getPsjgqrmz());
                skinComplexTime01.setText(this.skinTestDetailBean.getPsjgsj());
                skinComplexName02.setText(this.skinTestDetailBean.getFhmz());
                skinComplexTime02.setText(this.skinTestDetailBean.getFhsj());
                skinDetailEndLl02.setVisibility(View.GONE);
            } else {
                skinDetailEndLl02.setVisibility(View.VISIBLE);
                skinComplexName01.setText(PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_LOGNAME));
            }
        }
    }

    @Override
    public void startSkinTest(YXSkinTestExecBean yxSkinTestExecBean) {
        if (yxSkinTestExecBean.getHead().getRet_info().equals("成功")) {
            skinDetailTimeLl.setVisibility(View.GONE);
            int count = sharedPreferences.getInt("count", 0);
            if (count > 40000) {
                count = 0;
            }
            count++;
            setReminder(true, count);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putInt("count", count);
            editor.commit();
            presenter.showSkinTestDetail(psh);
        } else {
            ViewInject.toast("开始失败");
        }
    }

    @Override
    public void endSkinTest(YXSkinTestExecBean yxSkinTestExecBean) {
        if (yxSkinTestExecBean.getHead().getRet_info().equals("成功")) {
            presenter.showSkinTestDetail(psh);
        } else {
            ViewInject.toast("复合失败");
        }
    }

    private void initTimePicker(final int type) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String now = sdf.format(new Date());

        CustomDatePicker customDatePicker1 = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                if (type == 0) {
                    skinComplexTime01.setText(time);
                } else if (type == 1) {
                    skinComplexTime02.setText(time);
                }
            }
        }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker1.showSpecificTime(true); // 显示时和分
        customDatePicker1.setIsLoop(true); // 不允许循环滚动
        customDatePicker1.show(now);
    }

    private void selectIdea() {
        new ActionSheetDialog(aty)
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .addSheetItem("阴性", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                skinResult.setText("阴性");
                            }
                        })
                .addSheetItem("阳性", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                skinResult.setText("阳性");
                            }
                        })
                .addSheetItem("脱敏", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                skinResult.setText("脱敏");
                            }
                        }).show();
    }

    @Override
    public void loadingDialogStatus(int status) {
    }

    @Override
    public void loadingToastStatus(String Content) {
    }

    @Override
    public void doInLogin(YXLoginData yxLoginData) {
        skinComplexName02.setText(yxLoginData.getResponse().getEmpinfo().getLogname());
        loginDialog.dismiss();
    }

    @Override
    public void saveSystemListParams(SystemConfig systemConfig) {
    }

    /**
     * Set the alarm
     *
     * @param b whether enable the Alarm clock or not
     */
    private void setReminder(boolean b, int barcode) {

        // get the AlarmManager instance
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        // create a PendingIntent that will perform a broadcast
//        Intent intent = new Intent(i+"");
//        PendingIntent pi= PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
        Intent intent = new Intent(this, SkinTestReceiver.class);
        Bundle bundle = new Bundle();
        bundle.putString("id", barcode + "");
        bundle.putString("title", this.skinTestDetailBean.getPsmc());
        bundle.putString("name", PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_NAME));
        bundle.putString("subtxt", "皮试结束");
        intent.putExtras(bundle);
        PendingIntent pi = PendingIntent.getBroadcast(Act_SkinTest_Detail.this, barcode, intent, 0);

        if (b) {
            // just use current time + 10s as the Alarm time.
            Calendar c = Calendar.getInstance();
            c.setTimeInMillis(System.currentTimeMillis());
            //可以根据项目要求修改，秒、分钟、提前、延后
            c.add(Calendar.MINUTE, time);
            // schedule an alarm
            am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi);
        } else {
            // cancel current alarm
            am.cancel(pi);
        }

    }
}
